﻿using Bricks.Business.Models.Account;
using Bricks.Component.Utils;
using Bricks.Business.Data.Repositories.Account;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Bricks.Business.Data.Repositories.BidManagement;
using Bricks.Business.Models.BidManagement;
using Bricks.Business.Data.Repositories.ProjectContract;
using Bricks.Business.Data.Repositories.Document;
using Bricks.Business.Models.Document;
using Bricks.Site.Models.Document;
using Bricks.Business.Service.CommonSupport;
using Bricks.Component.Utils.Extensions;

namespace Bricks.Business.Service.Impl
{
    /// <summary>
    /// 文档
    /// </summary>
    [Export(typeof(IDocumentService))]
    public class DocumentService : IDocumentService
    {
        [Import]
        protected IDocumentInfoRepository DocumentInfoRepository { get; set; }

        public IQueryable<DocumentInfo> Documents
        {
            get { return DocumentInfoRepository.Entities; }
        }

        ///// <summary>
        ///// 新增
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public OperationResult Add(Document model)
        //{
        //    Document record = model.CopyTo<Document>();
        //    record.ID = GuidHelper.NewGuid();
        //    DocumentRepository.Insert(record);
        //    return new OperationResult(OperationResultType.Success, "新增成功", record);
        //}

        /// <summary>
        /// 删除（需关联删除标段）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(List<Guid> ids)
        {
            var records = Documents.Where(m => ids.Contains(m.ID));
            if (records == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            if (DocumentInfoRepository.Delete(records) >= 0)
                return new OperationResult(OperationResultType.Success, "删除成功", records);
            return new OperationResult(OperationResultType.Error, "删除失败");
        }

        ///// <summary>
        ///// 获取标段列表（根据招标ID）
        ///// </summary>
        ///// <param name="bidID"></param>
        ///// <returns></returns>
        //public List<SectionListView> GetSectionList(Guid bidID)
        //{
        //    List<SectionListView> result = new List<SectionListView>();
        //    //var sectionList = SectionInfoRepository.Entities.Where(m => m.BidID == bidID);
        //    //result = sectionList.OrderBy(m => m.AddDate).ToList();

        //    var sectionList = from m in SectionInfoRepository.Entities
        //                      where m.BidID == bidID
        //                      orderby m.AddDate
        //                      select new SectionListView
        //                      {
        //                          ID = m.ID,
        //                          SectionName = m.SectionName,
        //                          BidFile = m.BidFile,
        //                          BidUnit = m.BidUnit,
        //                          BidMoney = m.BidMoney,
        //                          EnterBidFile = m.EnterBidFile
        //                      };
        //    result = sectionList.ToList();
        //    return result;
        //}

        ///// <summary>
        ///// 保存标段列表
        ///// </summary>
        ///// <param name="bidID"></param>
        ///// <param name="list"></param>
        ///// <returns></returns>
        //public OperationResult SaveSectionList(Guid bidID, List<SectionListView> list)
        //{
        //    foreach (SectionListView view in list)
        //    {
        //        var record = SectionInfoRepository.Entities.FirstOrDefault(m => m.ID == view.ID);
        //        //编辑
        //        if (record != null)
        //        {
        //            record = view.CopyTo<SectionInfo>();
        //            record.BidID = bidID;
        //            SectionInfoRepository.Update(record);
        //        }
        //        //新增
        //        else
        //        {
        //            SectionInfo newSection = view.CopyTo<SectionInfo>();
        //            newSection.ID = GuidHelper.NewGuid();
        //            newSection.BidID = bidID;
        //            SectionInfoRepository.Insert(newSection);
        //        }
        //    }
        //    return new OperationResult(OperationResultType.Success, "保存成功");
        //}

        /// <summary>
        /// 保存文档列表
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="tag"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public OperationResult SaveDocumentList(Guid instanceID, string tag, List<DocumentView> list)
        {
            try
            {
                //清空对应的文件记录
                var existDocumentList = Documents.Where(m => m.InstanceID == instanceID && m.Tag == tag);
                if (existDocumentList != null)
                {
                    DocumentInfoRepository.Delete(existDocumentList);
                }

                //添加文件记录
                List<DocumentInfo> saveList = new List<DocumentInfo>();
                DocumentInfo newRecord = null;
                foreach (var item in list)
                {
                    newRecord = item.CopyTo<DocumentInfo>();
                    newRecord.InstanceID = instanceID;
                    newRecord.Tag = tag;
                    if (!item.UploadUserID.HasValue)
                    {
                        newRecord.UploadUserID = SystemData.Instance.CurrentUser.ID;
                    }
                    else
                    {
                        newRecord.UploadUserID = item.UploadUserID.Value;
                    }
                    //newRecord.AddDate = item.AddDate.Value;
                    newRecord.UploadTime = item.UploadTime;
                    saveList.Add(newRecord);
                }
                DocumentInfoRepository.Insert(saveList);
                return new OperationResult(OperationResultType.Success, "保存成功");
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
        }

        /// <summary>
        /// 保存通过百度editor直接上传的文件列表
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public OperationResult SaveRichTextBoxDocumentList(List<UEditorDocumentView> list, Guid instanceID, string attachmentTag)
        {
            try
            {
                //添加文件记录
                List<DocumentInfo> saveList = new List<DocumentInfo>();
                DocumentInfo newRecord = null;
                foreach (var item in list)
                {
                    newRecord = new DocumentInfo();
                    newRecord.InstanceID = instanceID;
                    newRecord.Tag = attachmentTag;
                    newRecord.FileName = item.original;
                    newRecord.FileSize = item.fileSize;
                    newRecord.FilePath = item.url;
                    newRecord.UploadUserID = item.uploadUserID.ToGuid();
                    newRecord.UploadTime = item.uploadTime;
                    saveList.Add(newRecord);
                }
                DocumentInfoRepository.Insert(saveList);
                return new OperationResult(OperationResultType.Success, "保存到文档表成功");
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, ex.Message);
            }
        }

        /// <summary>
        /// 获取文档信息（根据实例ID和标识Tag）
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public DocumentInfo GetDoumentInfo(Guid instanceID, string tag)
        {
            DocumentInfo result = new DocumentInfo();
            var document = Documents.FirstOrDefault(m => m.InstanceID == instanceID && m.Tag == tag);
            if (document != null)
                result = document;
            return result;
        }

        /// <summary>
        /// 根据实例删除（当删除记录时，需将关联的文档记录删除）
        /// </summary>
        /// <param name="instanceID"></param>
        /// <returns></returns>
        public bool DeleteByInstanceID(Guid instanceID)
        {
            var records = Documents.Where(m => m.InstanceID == instanceID);
            if (records != null)
            {
                if (DocumentInfoRepository.Delete(records) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
